import React, { useEffect, useState } from 'react'
import './index.less'
// import NavBar from '../../components/Navbar';
import { GetNickname } from '../../api/mine'
import { Input, Mask, Modal, Toast } from 'antd-mobile'
import { getRechangeMenu, requestH5Pay } from '../../api/recharge'
import { isWechat } from '../../utils/util'
import NavBar from '../../components/Navbar'

// 1182430
function ExchangeLog() {
  const [searchValue, setSearchValue] = useState('')
  const [menu, setMenu] = useState([])
  const [activeId, setActiveId] = useState()
  const [userInfo, setUserInfo] = useState()
  const [type, setType] = useState(1) // 1：支付宝 2：微信
  const [inputMoney, setInputMoney] = useState()
  const [aliPayForm, setAliPayForm] = useState()
  const [visible, setVisible] = useState(false)

  const [maskVisible, setMaskVisible] = useState(false)

  const getName = () => {
    if (!searchValue) {
      return false
    }
    if (Number.isNaN(Number(searchValue))) {
      Toast.show({ content: '请输入有效的用户ID' })
      return false
    }
    GetNickname({ user_id: searchValue })
      .then((res) => {
        console.log(res)
        setUserInfo(res.data)
      })
      .catch((err) => {
        setUserInfo(undefined)
        Toast.show({ content: err?.msg || err?.message || '系统错误' })
      })
  }

  const onFocus = () => {
    setActiveId(0)
  }

  const toPay = () => {
    if (!searchValue) {
      Toast.show({ content: '请输入要充值的用户ID' })
      return false
    }
    if (!inputMoney && !activeId) {
      Toast.show({ content: '请选择充值金额' })
      return false
    }
    Toast.show({
      content: '正在请求支付',
      icon: 'loading',
      maskClickable: false
    })
    requestH5Pay({
      type, // 1：支付宝 2：微信
      user_id: searchValue,
      price_num: inputMoney ? +inputMoney : 0,
      goods_id: activeId ? activeId : 0
    })
      .then((res) => {
        Toast.show({
          content: '正在拉起支付',
          icon: 'loading',
          maskClickable: false
        })
        if (type === 1 && res.data) {
          // window.location.href = res.data
          setAliPayForm(res.data)
          setTimeout(() => {
            document.forms['alipaysubmit'].submit()
          }, 100)
        }
        if (type === 2 && res.data) {
          window.location.href = res.data
        }
      })
      .catch((err) => {
        // Toast.clear();
        Toast.show({ content: err?.msg || err?.message })
      })
  }

  useEffect(() => {
    if (isWechat()) {
      setMaskVisible(true)
    } else {
      setMaskVisible(false)
    }
    getRechangeMenu().then((res) => {
      console.log(res)
      setMenu(res.data.goods)
    })
  }, [])

  const getPrice = (t) => {
    if (t === 'price') {
      if (inputMoney) return inputMoney
      return menu.find((i) => i.id === activeId)?.price
    }
    if (t === 'dou') {
      if (inputMoney) return +inputMoney * 10
      return menu.find((i) => i.id === activeId)?.mizuan
    }
    return null
  }

  const openModal = () => {
    if (!searchValue) {
      Toast.show({ content: '请输入要充值的用户ID' })
      return false
    }
    if (!inputMoney && !activeId) {
      Toast.show({ content: '请选择充值金额' })
      return false
    }
    setVisible(true)
  }

  return (
    <div className="h5-recharge_wrap">
      {/* <NavBar simple title="爱Dou充值" /> */}
      {!maskVisible ? (
        <div>
          <div className="user box">
            <div className="tit">用户信息</div>
            <p className="danger_txt">请仔细核对用户ID,误充不能退款,谢谢！</p>
            <div className="user-search">
              <div className="user_code">
                <Input
                  onBlur={getName}
                  maxLength={12}
                  onChange={setSearchValue}
                  value={searchValue}
                  type="text"
                  placeholder="请输入用户ID"
                />
              </div>
              <div className="search_btn" onClick={getName}>
                <span>查询</span>
              </div>
            </div>
            {userInfo ? (
              <div className="user_info">
                <span>{userInfo.nickname}</span>
              </div>
            ) : null}
          </div>
          <div className="recharge_list box">
            <div className="tit">充值金额</div>
            <div className="list_content">
              {menu.map((item) => (
                <div
                  onClick={() => {
                    setActiveId(item.id)
                    setInputMoney('')
                  }}
                  key={item.id}
                  className={`item ${activeId === item.id ? 'active' : ''} ${item.long ? 'long' : 'small'}`}
                >
                  <div className="point">
                    {item?.mizuan}
                    {window.baseConfig.coin_name}
                  </div>
                  <div className="price">{`¥${item?.price}`}</div>
                </div>
              ))}
            </div>
            <div className={`input_warp ${activeId === 0 ? 'active' : ''}`}>
              <div className="input">
                <Input
                  onFocus={onFocus}
                  onChange={(e) => {
                    setInputMoney(e.replace(/[^\d]/g, ''))
                  }}
                  maxLength={8}
                  value={inputMoney}
                  type="text"
                  placeholder="点击输入其它金额"
                />
              </div>
              {inputMoney && (
                <div className="income">
                  {Number(inputMoney) * 10}
                  {window.baseConfig.coin_name}
                </div>
              )}
              <div className="btn" onClick={openModal}>
                充值
              </div>
            </div>
            <div className="pay_way">
              <div className="">选择支付方式</div>
              <div className="way">
                <div className="pay_item" onClick={() => setType(2)}>
                  <div className={`select ${type === 2 ? 'selected' : ''}`}></div>
                  <div className="txt">微信支付</div>
                </div>
                <div className="pay_item" onClick={() => setType(1)}>
                  <div className={`select ${type === 1 ? 'selected' : ''}`}></div>
                  <div className="txt">支付宝</div>
                </div>
              </div>
            </div>
            <div className="warn_txt">
              <p>请仔细核对用户ID,误充不能退款,谢谢！</p>
              <p>微信额度上限，您可选择支付宝充值！</p>
              <p>请确保支付宝账号所属与{window.baseConfig.package_name}实名认证一致！</p>
              <p style={{ textDecorationLine: 'underline' }}>如遇诈骗或胁迫等违法行为，请即时报警避免造成财产损失</p>
            </div>
          </div>
        </div>
      ) : null}
      <Modal
        closeOnMaskClick
        onClose={() => setVisible(false)}
        forceRender={true}
        visible={visible}
        title="充值确认"
        content={
          <div className="mod_content">
            <div>
              <div className="avatar">
                <img src={userInfo?.headimgurl || ''} alt="" />
              </div>
              <div>昵称: {userInfo?.nickname}</div>
              <div style={{ margin: '12px 0' }}>
                充值: {getPrice('dou')}
                {window.baseConfig.coin_name} - ¥{getPrice('price')}
              </div>
              <div>充值渠道: {type === 1 ? '支付宝' : '微信'}</div>
            </div>
            <div className="action">
              <div className="btn cancel" onClick={() => setVisible(false)}>
                取消
              </div>
              <div className="btn confirm" onClick={toPay}>
                确定
              </div>
            </div>
          </div>
        }
      ></Modal>
      <div
        style={{ height: 0, width: 0, overflow: 'hidden' }}
        className="aliPay_form"
        dangerouslySetInnerHTML={{ __html: aliPayForm }}
      ></div>

      <Mask visible={maskVisible} opacity={0.45}>
        <div className="jump_box">点击左上角复制链接在浏览器打开</div>
      </Mask>
    </div>
  )
}

export default ExchangeLog
